<?php
class NHSChoicesAPIContoller {
	protected $self = array();
	
	public function NHSChoicesAPIContoller() {
		
	}
	
	public function __get($name = null) {
		if(!$this->self[$name]) {
			switch($name) {
				case 'username':
					$this->self[$name] = get_option('nhschoices_username');
					break;
				case 'password':
					$this->self[$name] = get_option('nhschoices_password');
					break;
				default:
					return null;
			}
		}
		
		return $this->self[$name];
	}
	
	function update_needed() {
		$cache_date = get_option('nhschoices_date_cached');
		
		if ($cache_date) {
			$cache_date = intval($cache_date);
			$now = mktime();
			$hours = floor(($now - $cache_date) / 60 / 60);
			return $hours >= 24;
		} else {
			return true;
		}
	}
	
	function clear_cache() {
		delete_option('nhschoices_date_cached');
	}
	
	function obtain_credentials() {
		global $STRAKT_API_URL;
		$url = $STRAKT_API_URL . '?key=' . get_option('nhschoices_api_key');
		$handle = fopen($url, 'r');
		$content = stream_get_contents($handle);
		fclose($handle);
		
		$json = json_decode($content, true);
		if($json['status'] == 'success') {
			$this->self['username'] = $json['username'];
			$this->self['password'] = $json['password'];
			
			update_option('nhschoices_username', $this->self['username']);
			update_option('nhschoices_password', $this->self['password']);
			
			return true;
		} else {
			return false;
		}
	}
	
	function get_results($service, $location, $rowcount = 10) {
		global $NHS_API_URL;
		$url = "$NHS_API_URL?user=$this->username&pwd=$this->password&q=" . urlencode($location) . "&type=$service&PageSize=$rowcount";
		
		$entries = simplexml_load_file($url);
		$results = array();
		
		foreach ($entries->Service as $entry) {
			$result = array(
				'guid' => $entry->Code1,
				'name' => $entry->Name,
				'service' => intval($entry->Type),
				'address1' => $entry->Address,
				'address2' => $entry->Address2,
				'address3' => $entry->Address3,
				'address4' => $entry->Address4,
				'address5' => $entry->Address5,
				'postcode' => $entry->Postcode,
				'telephone' => $entry->Telephone,
				'website' => $entry->Website,
				'latitude' => $entry->Latitude,
				'longitude' => $entry->Longitude,
				'distance' => $entry->Distance,
				'url' => $entry->ProviderProfilePageUrl,
			);
			
			$results[] = $result;
		}
		
		update_option('nhschoices_date_cached', mktime());
		return $results;
	}
}
?>